﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace _DataTable转Model
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Id", typeof(int));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Sex", typeof(string));
            dt.Columns.Add("Birthday", typeof(DateTime));
            dt.Columns.Add("InputTime", typeof(DateTime));

            DataRow dr = dt.NewRow();

            dr["Id"] = 1;
            dr["Name"] = "张三";
            dr["Sex"] = "男";
            dr["Birthday"] = DateTime.Now.AddYears(-20);
            dr["InputTime"] = DateTime.Now;
            dt.Rows.Add(dr);
            ///一行DataTable转Model
            Person p = GetModel2<Person>(dt);
        }


        public static Person GetModel(DataTable dt)
        {
            Person p = new Person();
            p.Id = Convert.ToInt32(dt.Rows[0]["Id"]);
            p.Name = dt.Rows[0]["Name"].ToString();
            p.Sex = dt.Rows[0]["Sex"].ToString();
            p.Birthday = Convert.ToDateTime(dt.Rows[0]["Birthday"]);
            p.InputTime = Convert.ToDateTime(dt.Rows[0]["InputTime"]);
            return p;
        }


        /// <summary>
        /// 通用返回Model
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="dt">DataTable数据</param>
        /// <returns>返回实体类</returns>
        public static T GetModel2<T>(DataTable dt) where T : new()
        {
            T t = new T();
            PropertyInfo[] info = typeof(T).GetProperties();
            foreach (PropertyInfo p in info)
            {
                p.SetValue(t, dt.Rows[0][p.Name]);
            }
            return t;
        }
    }
}
